package com.atguigu.gmall.item.config;

import com.atguigu.gmall.common.cache.GmallCacheAspect;
import com.atguigu.gmall.common.config.ItemServiceRedissonConfig;
import feign.Logger;
import lombok.Data;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * \
 * 工具类提取的所有的自动配置使用@Import即可
 * 导入自己的 GmallCacheAspect.class 分布式缓存切面
 *
 * @author dyqstart
 * @create 2021-08-10-19:19
 * @since 1.0.0
 */
@Import({ItemServiceRedissonConfig.class, GmallCacheAspect.class})
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableAspectJAutoProxy  //开启切面功能
@Configuration
public class ItemConfig {

    /**
     * 开启feign的追踪日志排错
     * 1、配置feign接口所在的包的日志级别
     * logging:
     *   level:
     *     com.atguigu.gmall.feign.product: debug
     *
     *  2、配置日志组件
     *      @Bean
     *     Logger.Level feignLoggerLever(){
     *         return Logger.Level.FULL;
     *     }
     * @return
     */
    @Bean
    Logger.Level feignLoggerLever(){
        return Logger.Level.FULL;
    }


    @Component
    @ConfigurationProperties(prefix = "item-service.thread")
    @Data
    class ThreadConfigProperties {
        private Integer core;
        private Integer max;
        private Long keepalive;
        private Integer queueLength;
    }

    //核心业务线程池
    @Bean("corePool")
    public ThreadPoolExecutor executor(ThreadConfigProperties properties) {
        return new ThreadPoolExecutor(
                properties.core,
                properties.max,
                properties.keepalive,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(properties.queueLength),
//                Executors.defaultThreadFactory(),
                new MyItemServiceThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }


    class MyItemServiceThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {

            Thread thread = new Thread(r);
            thread.setName("item-service: " + UUID.randomUUID().toString().substring(0, 5));
            return thread;
        }
    }
}
